<template>
  <div class="app-container">
    <!--条件搜索表单-->
    <el-row :gutter="20">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchObj.username" placeholder="用户名称" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchObj.sex" placeholder="用户性别" clearable @change="getAll()">
            <el-option v-for="item in sexOptions" :key="item.value" :label="item.text" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchObj.email" placeholder="用户邮箱" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchObj.phone" placeholder="手机号码" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchObj.status" placeholder="用户状态" clearable @change="getAll()">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.text" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getAll()">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reset()">清空</el-button>
      </el-form>
    </el-row>
    <el-row :gutter="20" style="margin-top: 10px">
      <el-button v-if="hasPerm('sys:user:save')" type="primary" icon="el-icon-plus" @click="openEdit(null)">新增</el-button>
      <el-button v-if="hasPerm('sys:user:batch-delete')" type="danger" icon="el-icon-delete" :disabled="ids.length < 1" @click="batchDelete">
        批量删除
      </el-button>
    </el-row>

    <!-- banner列表 :data="list"表示遍历list数组 stripe条纹 -->
    <el-table
      v-loading="loading"
      element-loading-text="正在努力加载数据中..."
      :data="page.records"
      :border="false"
      stripe
      style="width: 100%; margin: 15px 0px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" fixed="left" width="55" />
      <el-table-column type="index" fixed="left" width="80" label="序号" />
      <el-table-column prop="username" fixed="left" label="用户名称" min-width="100" sortable show-overflow-tooltip />
      <el-table-column prop="nickname" label="用户昵称" show-overflow-tooltip />
      <el-table-column prop="sex" label="用户性别" min-width="100" :filters="sexOptions" :filter-method="filterHandler">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sex === 0" type="success">男</el-tag>
          <el-tag v-if="scope.row.sex === 1" type="danger">女</el-tag>
          <el-tag v-if="scope.row.sex === 2" type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱地址" show-overflow-tooltip />
      <el-table-column prop="phone" label="手机号码" min-width="100" sortable show-overflow-tooltip />
      <el-table-column prop="priority" label="优先级" min-width="90" sortable />
      <el-table-column prop="status" label="用户状态" min-width="120" sortable :filters="statusOptions" :filter-method="filterHandler">
        <template slot-scope="scope">
          <div v-if="!hasPerm('sys:user:update-status')">
            <el-tag v-if="scope.row.status === 0" type="primary">正常</el-tag>
            <el-tag v-if="scope.row.status === 1" type="danger">停用</el-tag>
          </div>
          <el-switch
            v-if="hasPerm('sys:user:update-status')"
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" show-overflow-tooltip />
      <el-table-column prop="lastLoginTime" label="最后登录时间" min-width="140" sortable show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" min-width="100" sortable show-overflow-tooltip />

      <!-- 操作 -->
      <el-table-column
        v-if="hasPerm('sys:user:update', 'sys:user:delete', 'sys:user:reset-password', 'sys:user:assign-role')"
        label="操作"
        width="220"
        fixed="right"
        align="center"
      >
        <template slot-scope="scope">
          <el-link v-if="hasPerm('sys:user:update')" type="success" icon="el-icon-edit" @click="openEdit(scope.row)">编辑</el-link>
          <el-divider v-if="hasPerm('sys:user:update')" direction="vertical" />
          <el-link v-if="hasPerm('sys:user:delete')" type="danger" icon="el-icon-remove" @click="remove(scope.row.id)">删除</el-link>
          <el-divider v-if="hasPerm('sys:user:delete')" direction="vertical" />
          <el-dropdown v-if="hasPerm('sys:user:reset-password', 'sys:user:assign-role')">
            <el-link type="primary" icon="el-icon-more">更多</el-link>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-link v-if="hasPerm('sys:user:reset-password')" type="warning" icon="el-icon-key" @click="resetPassword(scope.row)">
                  重置密码
                </el-link>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-link v-if="hasPerm('sys:user:assign-role')" type="info" icon="el-icon-circle-check" @click="openAssignRole(scope.row)">
                  分配角色
                </el-link>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页导航栏 -->
    <div>
      <el-pagination
        :background="true"
        :current-page="pIndex"
        :page-size="pSize"
        :total="page.total"
        :page-sizes="[1, 3, 6, 9, 12, 15, 18]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        @current-change="getAll"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 表单 -->
    <el-dialog v-if="hasPerm('sys:user:save', 'sys:user:update')" :title="dialogTitle" :visible.sync="visible" @close="close('userForm')">
      <el-form ref="userForm" :rules="rules" :model="user" label-width="100px">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="ID" prop="id" :hidden="true">
              <el-input v-model="user.id" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户名称" prop="username" required>
              <el-input v-model="user.username" placeholder="请输入用户名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item v-show="user.id ? false : true" label="用户密码" prop="password">
              <el-input v-model="user.password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户昵称" prop="nickname" required>
              <el-input v-model="user.nickname" placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="user.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="电话号码" prop="phone">
              <el-input v-model="user.phone" placeholder="请输入电话号码" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="user.sex" placeholder="请选择性别" style="width: 100%">
                <el-option v-for="item in sexOptions" :key="item.value" :label="item.text" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="user.status" style="width: 100%">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.text" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="优先级" prop="priority">
              <el-input-number v-model="user.priority" controls-position="right" placeholder="请输入优先级" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="用户角色" prop="roleIds">
              <el-select v-model="user.roleIds" placeholder="请选择角色" clearable multiple style="width: 100%">
                <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="用户备注" prop="remark">
              <el-input v-model="user.remark" :rows="3" type="textarea" placeholder="请输入备注" maxlength="255" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close('userForm')">取 消</el-button>
        <el-button type="primary" @click="save('userForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog v-if="hasPerm('sys:user:assign-role')" title="分配角色" :visible.sync="assignRoleVisible" @close="assignRoleVisible = false">
      <el-form :model="assignRole" label-width="100px">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="ID" prop="id" :hidden="true">
              <el-input v-model="assignRole.userId" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户名称">
              <el-input v-model="assignRole.username" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户昵称">
              <el-input v-model="assignRole.nickname" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="用户角色" prop="roleIds">
              <el-select v-model="assignRole.roleIds" placeholder="请选择角色" clearable multiple style="width: 100%">
                <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入api接口定义的js文件
import userApi from '@/api/sys/user'
import roleApi from '@/api/sys/role'

export default {
  data() {
    // 定义变量和初始值
    return {
      // 性别选项
      sexOptions: [
        { value: 0, text: '男' },
        { value: 1, text: '女' },
        { value: 2, text: '未知' }
      ],
      // 状态选项
      statusOptions: [
        { value: 0, text: '正常' },
        { value: 1, text: '停用' }
      ],
      // 查询条件
      searchObj: {},

      // 列表相关
      loading: false, // 加载状态
      pIndex: 1, // 当前页
      pSize: 6, // 每页显示记录数
      page: [], // 列表
      ids: [], // 选中的列ID

      // 表单相关
      dialogTitle: '',
      visible: false, // 是否显示表单
      user: {
        id: undefined,
        username: '',
        password: '123456',
        nickname: '',
        email: '',
        phone: '',
        sex: 2,
        roleIds: [],
        status: 0,
        priority: 0,
        remark: ''
      },
      // 验证规则
      rules: {
        username: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
        nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '邮箱格式错误', trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '手机号码格式错误',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 角色
      roles: [],
      // 分配角色
      assignRoleVisible: false,
      assignRole: {
        userId: undefined,
        roleIds: []
      }
    }
  },
  created() {
    this.getAll()
  },
  methods: {
    // 获取所有角色
    getRoles() {
      roleApi.getList().then((res) => {
        this.roles = res.data
      })
    },

    // 加载列表数据
    getAll(current = 1) {
      this.loading = true
      this.pIndex = current
      userApi
        .getPage(this.pIndex, this.pSize, this.searchObj)
        .then((response) => {
          this.page = response.data
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 行内筛选
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },

    // 改变页码
    handleSizeChange(pageSize) {
      this.pSize = pageSize
      // 重新调用数据加载方法 --> 方法中已经加入的查询参数
      this.getAll()
    },

    // 改变状态
    handleStatusChange(row) {
      const text = row.status === 0 ? '正常' : '停用'
      this.$confirm(`此操作将修改 '${row.username}' 状态为 '${text}', 是否继续?`, '用户状态修改', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          userApi
            .updateStatus(row.id, row.status)
            .then((resp) => {
              this.$message.success('操作成功！')
            })
            .catch(() => {
              row.status = row.status === 0 ? 1 : 0
            })
        })
        .catch(() => {
          row.status = row.status === 0 ? 1 : 0
        })
    },

    // 删除用户信息
    remove(id) {
      this.$confirm('此操作将永久删除用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          userApi.deleteById(id).then((resp) => {
            this.$message.success('删除成功！')
            this.getAll()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除！')
        })
    },

    // 复选框选中
    handleSelectionChange(r) {
      // 得到选中的id
      this.ids = r.map((v) => v.id)
    },

    // 打开表单页面
    openEdit(row) {
      this.getRoles()
      this.dialogTitle = '新增用户'
      this.visible = true
      this.user.priority = this.page.total + 2

      if (row != null) {
        this.dialogTitle = '编辑用户'
        userApi.getById(row.id).then((res) => {
          const data = res.data
          Object.assign(this.user, data)
          this.user.roleIds = data.roles.map((v) => v.id)
        })
      }
    },

    // 关闭表单
    close(form) {
      this.visible = false
      this.$refs[form].resetFields()
    },

    // 保存
    save(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const apiCall = this.user.id ? userApi.update(this.user) : userApi.save(this.user)
          apiCall.then(() => {
            this.$message.success('操作成功')
            this.close(form)
            this.getAll()
          })
        }
      })
    },

    // 批量删除
    batchDelete() {
      if (this.ids.length > 0) {
        this.$confirm('此操作将永久删除用户信息,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          // 确定执行then方法
          .then(() => {
            userApi.batchDelete(this.ids).then((resp) => {
              this.$message.success('删除成功！')
              this.getAll()
            })
          })
          .catch(() => {
            this.$message.info('已取消删除！')
          })
      } else {
        this.$message.warning('至少选择一条数据!')
      }
    },

    // 重置
    reset() {
      this.searchObj = {}
      this.getAll()
    },

    // 重置密码
    resetPassword(r) {
      this.$confirm(`此操作将重置 ${r.nickname} 的密码,是否继续?`, '提示', {
        title: '重置密码',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        // 确定执行then方法
        .then(() => {
          userApi.resetPassword(r.id).then((resp) => {
            this.$message.success('重置成功！')
            this.getAll()
          })
        })
        .catch(() => {
          this.$message.info('已取消重置！')
        })
    },

    // 分配角色
    openAssignRole(r) {
      this.assignRoleVisible = true
      this.assignRole.userId = r.id
      this.assignRole.username = r.username
      this.assignRole.nickname = r.nickname
      this.assignRole.roleIds = r.roles.map((v) => v.id)
    },

    // 保存角色
    saveRole() {
      userApi
        .assignRole(this.assignRole)
        .then((res) => {
          this.assignRoleVisible = false
          this.getAll()
          this.$message.success('分配成功！')
        })
        .catch((err) => {
          console.log('save role err', err)
        })
    }
  }
}
</script>

<style></style>
